﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace NfsCommon.Export
{
    public class StringUtil
    {
        private static string key = null;

        public static string Key
        {
            get
            {
                if (key == null)
                {
                    GenerateKey();
                }
                return key;
            }
        }

        private static void GenerateKey()
        {
            int[] indexs = new int[8] { 17, 38, 25, 35, 2, 0, 0, 8 };
            key = "";

            for (int i = 0; i < indexs.Length; i++)
            {
                char chr = '0';
                chr = Convert.ToChar(Convert.ToInt32(chr) + indexs[i]);
                key += chr;
            }
        }

        public static string Encrypt(string text)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            byte[] inputByteArray = Encoding.UTF8.GetBytes(text);
            des.Key = ASCIIEncoding.ASCII.GetBytes(Key);
            des.IV = ASCIIEncoding.ASCII.GetBytes(Key);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            byte[] en_bytes = ms.ToArray();
            return Convert.ToBase64String(en_bytes);
        }

        public static string Decrypt(string text)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            byte[] inputByteArray = Convert.FromBase64String(text);
            des.Key = ASCIIEncoding.ASCII.GetBytes(Key);
            des.IV = ASCIIEncoding.ASCII.GetBytes(Key);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            StringBuilder ret = new StringBuilder();
            return System.Text.Encoding.UTF8.GetString(ms.ToArray());

        }
    }
}
